package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void saveOrUpdate(Role role,Long[] ids) {
        if(role.getId() != null){
            //先删除关系,再修改,再保存新关系
            roleMapper.deleteRelation(role.getId());
            roleMapper.updateByPrimaryKey(role);
        }else {
            //先新增返回id再保存关系
            roleMapper.insert(role);
        }
        //保存新关系
        if(ids != null && ids.length > 0){
            roleMapper.saveRelation(role.getId(),ids);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if(id != null){
            //先删除中间表关系
            //删除角色和权限的中间表
            roleMapper.deleteRelation(id);
            //删除角色和员工的中间表
            roleMapper.deleteRelationWithEmployee(id);
            //删除角色
            roleMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public Role selectOne(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    @Override
    public PageInfo<Role> queryPage(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Role> roles = roleMapper.queryPage(qo);
        return new PageInfo<>(roles);
    }
}
